package api

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"two_exam/config"
	"two_exam/internal/model/dao"
	"two_exam/internal/model/request"
	"two_exam/internal/model/service"
)

func AddUser(c *gin.Context) {
	userName := c.PostForm("userName")
	user := dao.UserChat{
		UserName: userName,
	}
	config.DB.Create(&user)
}

func UserList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "0"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "5"))
	name := c.DefaultQuery("name", "")
	list, err := service.List(page, pageSize, name)
	if err != nil {
		return
	}
	c.JSON(http.StatusOK, gin.H{"code": 200, "message": "成功", "data": list})
}

func UserFriendAdd(c *gin.Context) {
	var form request.FriendForm
	err := c.ShouldBind(&form)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "参数获取失败"})
		return
	}
	exists := service.FindUserIsExists(form.UserName)
	if !exists {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "用户不存在"})
		return
	}
	//是否是好友
	friend := service.IsExistsFriend(form.UserId, form.FriendId)
	if friend {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "两人已经是好友"})
		return
	}
	err = service.AddFriend(form.UserId, form.FriendId)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "好友添加失败"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"message": "好友添加成功"})
}
